package breadbox.demo;

import java.net.InetAddress;
import java.util.Scanner;

import breadbox.pastry.Application;
import breadbox.pastry.Message;
import breadbox.pastry.Node;
import breadbox.pastry.PastryNode;
import breadbox.pastry.routing.LeafSet;
import breadbox.pastry.routing.RoutingNode;

public class ChatApplication implements Application {
	private String name;
	private LeafSet leaves;
	
	public static void main (String[] args) {
		ChatApplication chat = new ChatApplication(args[0]);
		
		Node node = PastryNode.getPastryNode();
		node.register(chat);
		node.open();
		node.join();
		
		chat.chat();
	}
	
	public ChatApplication(String name) {
		this.name = name;
	}
	
	public void chat() {
		Node node = PastryNode.getPastryNode();
		Scanner s = new Scanner(System.in);
		System.out.println("Ready to chat " + this.name);
		while (s.hasNextLine()) {
			 String line = s.nextLine();
			 if (line.equalsIgnoreCase("exit")) {
				 node.close();
				 break;
			 } else if (line.equalsIgnoreCase("list")) {
				 if (this.leaves != null) {
					 System.out.println("Online Ids:");
					 RoutingNode[] list = this.leaves.toArray();
					 if (list != null && list.length != 0) {
						 for(RoutingNode r : list) {
							 System.out.println("\tID:" + r.getId() + "; IP:" + r.getIp() + "; Port:" + r.getPort());
						 }
					 }
				 } else {
					 System.out.println("No nodes found");
				 }
			 } else if (!line.equalsIgnoreCase("")) {
				 Message m = new Message((long)(Math.random()*Long.MAX_VALUE), "text", (this.name + ": " + line).getBytes());
				 node.route(m);
				 System.out.println("Me: " + line);
			 }
		}
	}

	public void deliver(Message m) {
		String msg = new String(m.data);
		System.out.println(msg);
	}

	public void forward(Message m) {
		String msg = new String(m.data);
		System.out.println("Forwarded: " + msg);
	}

	public void newLeaf(LeafSet l) {
		this.leaves = l;
		System.out.println("New Leaf");
	}

	public int proximity(InetAddress ip, int port) {
		// TODO Auto-generated method stub
		return 0;
	}
}
